package com.dwxt.community.admin.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.IntegralCategory;
import com.dwxt.common.util.DateUtils;
import com.dwxt.common.util.ExcelUtils;
import com.dwxt.community.dao.IntegralRecordMapper;
import com.dwxt.community.dao.IntegralRuleMapper;
import com.dwxt.community.entity.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class IntegralServiceAdmin {

    @Autowired
    private IntegralRecordMapper integralRecordMapper;

    @Autowired
    private IntegralRuleMapper integralRuleMapper;

    public List<IntegralRecord> selectIntegralList(String userId) {
        IntegralRecordExample example = new IntegralRecordExample();
        example.setOrderByClause("create_time desc");
        example.createCriteria().andUserIdEqualTo(userId);

        return integralRecordMapper.selectByExample(example);
    }

    public List<IntegralRule> selectAllRule() {
        IntegralRuleExample example = new IntegralRuleExample();
        return integralRuleMapper.selectByExample(example);
    }

    public void updateRule(IntegralRule rule) {
        integralRuleMapper.updateByPrimaryKeySelective(rule);
    }

    public List<OfflineActivity> selectLineActivityRecord() {
        return integralRecordMapper.selectLineActivityRecord();
    }

    public void insertActivityRecord(OfflineActivity offlineActivity) {
        IntegralRecord record = new IntegralRecord();
        record.setCategory(offlineActivity.getName());
        record.setIntegral(offlineActivity.getIntegral());
        record.setUserId("0");
        record.setYear(DateUtils.getYear(null));
        record.setMonth(DateUtils.getMonth(null));
        record.setDay(DateUtils.getDay(null));
        record.setRelateId("activity_" + offlineActivity.getId());
        integralRecordMapper.insertSelective(record);
    }

    public IntegralRecord selectByRelateId(Integer id) {
        IntegralRecordExample example = new IntegralRecordExample();
        example.createCriteria().andRelateIdEqualTo("activity_" + id);
        List<IntegralRecord> integralRecordList = integralRecordMapper.selectByExample(example);
        return integralRecordList.size() > 0 ? integralRecordList.get(0) : null;
    }

    public void updateRecord(IntegralRecord record) {
        integralRecordMapper.updateByPrimaryKeySelective(record);
    }

    public void deleteByRelateId(Integer id) {
        IntegralRecordExample example = new IntegralRecordExample();
        example.createCriteria().andRelateIdEqualTo("activity_" + id);
        integralRecordMapper.deleteByExample(example);
    }


    public BaseResult integralStatistics() {
        //行为积分
        Integer behaviorIntegral = integralRecordMapper.sumByCategory(IntegralCategory.GARBAGE_DUMP);
        //线上活动积分
        Integer register = integralRecordMapper.sumByCategory(IntegralCategory.REGISTER);
        Integer complete = integralRecordMapper.sumByCategory(IntegralCategory.COMPLETE__INFORMATION);
        //线下活动积分
        Integer activity = integralRecordMapper.sumByUserId("0");

        Map map = new HashMap();
        map.put("activityIntegral", register + complete + activity);
        map.put("behaviorIntegral", behaviorIntegral);

        return BaseResult.ok(map);
    }

    public BaseResult selectIntegralStatistics() {
        Integer plus = integralRecordMapper.sumPlusIntegral();
        Integer negative = integralRecordMapper.sumNegativeIntegral();

        Map map = new HashMap();
        map.put("plus", plus);
        map.put("negative", negative);

        return BaseResult.ok(map);
    }

    public BaseResult selectIntegralStatisticsByActive() {
        List<Map> mapList = integralRecordMapper.selectIntegralStatisticsByActive();
        return BaseResult.ok(mapList);
    }

    public BaseResult selectIntegralStatisticsByTime(Integer year, Integer month) {
        List<Map> mapList = integralRecordMapper.selectIntegralStatisticsByTime(year, month);
        return BaseResult.ok(mapList);
    }

    public BaseResult selectIntegralStatisticsByUser(String phone, Integer pageNum, Integer pageSize,
                                                     Integer type, String sequence) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map> mapList = integralRecordMapper.selectIntegralStatisticsByUser(phone,type,sequence);
        PageInfo<Map> pageInfo = new PageInfo<>(mapList);
        return BaseResult.ok(pageInfo);
    }

    public void export(Integer type, Integer year, Integer month, String phone, HttpServletResponse response) {
        List<Map> list = new ArrayList<>();
        List<String> strings = new ArrayList<>();
        if (type == 1) {
            list = integralRecordMapper.selectIntegralStatisticsByActive();
            strings.add("活动名称");
            strings.add("活动类型");
            strings.add("发放积分");
        } else if (type == 2) {
            list = integralRecordMapper.selectIntegralStatisticsByTime(year, month);
            strings.add("时间");
            strings.add("发放积分数");
            strings.add("使用积分数");
        } else {
            list = integralRecordMapper.selectIntegralStatisticsByUser(phone, type, phone);
            strings.add("电话号码");
            strings.add("获得积分数");
            strings.add("使用积分数");
        }
        //List<TrashIntegralRecoadVo> list = trashIntegralRecoadMapper.selectAll(trashIntegralRecoad);
        if (ObjectUtils.isNotEmpty(list)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //excel标题
            String[] title = strings.toArray(new String[strings.size()]);
            //excel文件名
            String fileName = "积分记录表" + System.currentTimeMillis() + ".xls";

            //sheet名
            String sheetName = "积分记录表";
            String[][] content = new String[list.size()][3];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[title.length];
                Map map = list.get(i);
                if (type == 1) {
                    content[i][0] = map.get("name").toString();
                    content[i][1] = "1".equals(map.get("isOn").toString()) ? "线上活动" : "线下活动";
                    content[i][2] = map.get("total").toString();
                } else if (type == 2) {
                    content[i][0] = map.get("year").toString() + "年" + map.get("month").toString() + "月";
                    content[i][1] = map.get("plus").toString();
                    content[i][2] = map.get("negative").toString();
                } else {
                    content[i][0] = map.get("phone").toString();
                    content[i][1] = map.get("plus").toString();
                    content[i][2] = map.get("negative").toString();
                }

            }

            //创建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
            //响应到客户端
            try {
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.setHeader("Content-disposition", "attachment; filename=" + fileName);
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public List<Map> selectTotalIntegralStatistics() {
        return integralRecordMapper.selectTotalIntegralStatistics();
    }

    public List<Map> selectPlusAndNegativeIntegral(String date) {
        return integralRecordMapper.selectPlusAndNegativeIntegral(date);
    }
}
